import axiosInstance from "../../plugins/axios";
import { ElMessage } from "element-plus";
import { NoticeDTO } from "../../type/Notice";

export const getNoticeInfo = async (pageNum: number, pageSize: number) => {
    const res = await axiosInstance.post(
      `/notices/page?pageNum=${pageNum}&pageSize=${pageSize}`
    );
    if (res.data.code == 1) {
      return res.data.data; // 返回数据
    } else {
      ElMessage.error(res.data.message || "获取通知信息失败");
      throw new Error(res.data.message || "获取通知信息失败");
    }
  };

  export const searchNoticeInfo = async (
    pageNum: number,
    pageSize: number,
    search: any
  ) => {
    const res = await axiosInstance.post("/notices/search", {
      pageNum,
      pageSize,
      search,
    });
    if (res.data.code === 1) {
      return res.data.data; // 返回数据
    } else {
      ElMessage.error(res.data.message || "搜索通知信息失败");
      throw new Error(res.data.message || "搜索通知信息失败");
    }
  };

  export const publishNotice = async (noticeDTO: NoticeDTO) => {
    const res = await axiosInstance.post("/notices/publish", noticeDTO);
    if (res.data.code === 1) {
      return res.data.data; // 返回数据
    } else {
      ElMessage.error(res.data.message || "发布通知失败");
      throw new Error(res.data.message || "发布通知失败");
    }
  };

  export const exportNoticeInfo = async () => {
    axiosInstance
      .get("/notices/export", {
        responseType: "blob", // 重要
      })
      .then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement("a");
        link.href = url;
        const contentDisposition = response.headers["content-disposition"];
        let fileName = "下载文件.xlsx";
        if (contentDisposition) {
          const fileNameMatch = contentDisposition.match(
            /filename\*=UTF-8''(.+)/
          );
          if (fileNameMatch.length === 2) {
            fileName = decodeURIComponent(fileNameMatch[1]);
          }
        }
        link.setAttribute("download", fileName);
        document.body.appendChild(link);
        link.click();
        link.remove();
      })
      .catch((error) => {
        ElMessage.error("下载失败，请重试");
        console.error("下载失败:", error);
      });
  };

  export const deleteNotice = async (noticeDTO: NoticeDTO) => {
    const res = await axiosInstance.post("/notices/delete", noticeDTO);
    if (res.data.code === 1) {
      return res.data.data; // 返回数据
    } else {
      ElMessage.error(res.data.message || "删除通知失败");
      throw new Error(res.data.message || "删除通知失败");
    }
  };